﻿using PPIDesktopClient.Entities;
using PPIDesktopClient.General;
using PPIDesktopClient.Logic;
using PPIMobileInterface.Logic;
using System;
using System.Data;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace PPIDesktopClient
{
    public partial class frmPoleEditor : frmDialogBase
    {
        #region Fields

        private Int32 m_Id;
        private EBaseAsset m_CurrentAsset = null;

        private EVendor_Visit_XMissionStructure m_SelectedStructure = null;
        private List<EVendor_Visit_XMissionStructures_Image> m_ImagesCurrentPole;
        private int m_MobileAssetID = Int32.MinValue;
        private string m_MobileDatabaseConnectionString;
        private bool m_IsMobileAsset;


        #endregion

        #region Properties
        public Int32 Id
        {
            get
            {
                return m_Id;
            }
            set
            {
                m_Id = value;
            }
        }

        public EVendor_Visit_XMissionStructure Structure
        {
            get { return m_SelectedStructure; }
            set { m_SelectedStructure = value; }
        }

        public int MobileAssetID
        {
            get { return m_MobileAssetID; }
            set { m_MobileAssetID = value; }
        }

        public string MobileDatabaseConnectionString
        {
            get { return m_MobileDatabaseConnectionString; }
            set { m_MobileDatabaseConnectionString = value; }
        }

        public bool IsMobileAsset
        {
            get { return (m_MobileAssetID != Int32.MinValue); }
        }

        #endregion

        #region Events

        #region Form

        private void frmPoleEditor_Load(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                Application.DoEvents();
                this.btnSave.Enabled = true;
                this.btnCancel.Enabled = true;
                this.pbSave.Visible = false;

                CleanStructureData();


                LoadCombos();
                CleanPoleControls();
                ddlImagesPole.Items.Clear();
                m_ImagesCurrentPole = new List<EVendor_Visit_XMissionStructures_Image>();

                ddlImagesPole.SelectedIndex = -1;
                lstPoles.Items.Clear();

                if (IsMobileAsset)
                {
                    m_SelectedStructure = SelectMobileStructure(MobileAssetID);
                    LoadStructureData(m_SelectedStructure);
                }
                else
                {
                    if (m_Id != Int32.MinValue)
                    {
                        m_SelectedStructure = SelectStructure(m_Id);
                        LoadStructureData(m_SelectedStructure);
                    }
                }
                this.Cursor = Cursors.Default;

            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmPoleEditor.frmPoleEditor_Load", ex.Source, ex.Message, ex.StackTrace);
                throw new Exception(ex.Message);
            }
        }


        #endregion

        #region Controls

        private void btnDeleteImage_Click(object sender, EventArgs e)
        {
            RemoveImage();
            CleanPictureBox();
        }

        private void btnSearchImage_Click(object sender, EventArgs e)
        {

            try
            {
                OpenFileDialog _OpenFileDialog = new OpenFileDialog();
                DialogResult _DialogResult = _OpenFileDialog.ShowDialog();
                EVendor_Visit_XMissionStructures_Image _Image;
                FileInfo _SelectedFile;
                switch (_DialogResult)
                {
                    case DialogResult.OK:
                    case DialogResult.Yes:
                        _SelectedFile = new FileInfo(_OpenFileDialog.FileName);
                        _Image = new EVendor_Visit_XMissionStructures_Image();
                        _Image.File = _SelectedFile;
                        _Image.Asset = m_SelectedStructure;
                        _Image.Pole = new EVendor_Visit_XMissionStructures_Pole();
                        ddlListImages.Items.Add(_Image);
                        ddlImagesPole.Items.Add(_Image);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmPoleEditor.btnSearchImage_Click()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private void ddlListImages_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlListImages.SelectedItem != null)
                {
                    EVendor_Visit_XMissionStructures_Image i = (EVendor_Visit_XMissionStructures_Image)ddlListImages.SelectedItem;
                    showImageinPicturebox(i.File, pbxSelectedImage);
                }
            }
            catch (Exception)
            {

                throw;
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstPoles.Items.Count == 0)
                {
                    lblErrorOnePole.Visible = true;
                    lblOtherErrors.Text = lblErrorOnePole.Text;
                    lblOtherErrors.Visible = true;
                }

                else
                {
                    lblErrorOnePole.Visible = false;
                    lblOtherErrors.Visible = false;
                }
                    
                if (ValidateControls() && !lblErrorOnePole.Visible)
                {
                    CleanPictureBox();
                    this.pbSave.Visible = true;
                    EVendor_Visit_XMissionStructure _Vendor_Visit_XMissionStructure = SaveStructure();
                    SaveImages(_Vendor_Visit_XMissionStructure);
                    SavePoles(_Vendor_Visit_XMissionStructure);
                    m_SelectedStructure = _Vendor_Visit_XMissionStructure;
                    SaveAssetProcess _SaveProcess = new SaveAssetProcess(m_SelectedStructure);
                    _SaveProcess.SaveProgressChanged += new EventHandler<System.ComponentModel.ProgressChangedEventArgs>(_SaveProcess_SaveProgressChanged);
                    _SaveProcess.SaveCompleted += new EventHandler(_SaveProcess_SaveCompleted);
                    _SaveProcess.StartProcess();
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = false;
                }

            }
            catch (Exception ex)
            {
                ErrorManager.Log("Exception", ex.Source, ex.Message, ex.StackTrace);
            }




        }

        private void btnAddImagePole_Click(object sender, EventArgs e)
        {
            if (ddlImagesPole.SelectedItem != null)
            {
                EVendor_Visit_XMissionStructures_Image i = (EVendor_Visit_XMissionStructures_Image)ddlImagesPole.SelectedItem;
                if (i.IsDesasocciated)
                {
                    if (!lstImagesPoles.Items.Contains(i))
                    {
                        showImageinPicturebox(i.File, pbxPoleImagePreview);
                        i.IsDesasocciated = false;
                        lstImagesPoles.Items.Add(i);
                        m_ImagesCurrentPole.Add(i);
                    }

                }
            }
        }

        private void ddlImagesPole_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlImagesPole.SelectedItem != null)
            {
                EVendor_Visit_XMissionStructures_Image i = (EVendor_Visit_XMissionStructures_Image)ddlImagesPole.SelectedItem;
                showImageinPicturebox(i.File, pbxSelectedImage);
            }
        }

        private void lstPoles_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstPoles.SelectedItem != null)
            {
                CleanPoleControls();
                btnAddPole.Text = "Update";
                LoadPoleData((EVendor_Visit_XMissionStructures_Pole)lstPoles.SelectedItem);
            }
        }

        private void lstImagesPoles_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstImagesPoles.SelectedItem != null)
            {
                EVendor_Visit_XMissionStructures_Image i = (EVendor_Visit_XMissionStructures_Image)lstImagesPoles.SelectedItem;
                showImageinPicturebox(i.File, pbxPoleImagePreview);
            }
        }

        private void btnAddPole_Click(object sender, EventArgs e)
        {
            if (ctrlPositionPoles.ValidatePosition() && ValidateControls())
            {
                AddPoleToListbox(lstPoles);
                CleanPoleControls();
                btnAddPole.Text = "Add Pole";
                lstPoles.ClearSelected();
            }
        }

        private void btnClearPole_Click(object sender, EventArgs e)
        {
            CleanPoleControls();
            btnAddPole.Text = "Add Pole";
            lstPoles.ClearSelected();

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            m_IsMobileAsset = false;
            m_MobileAssetID = Int32.MinValue;
            m_SelectedStructure = null;
            m_Id = Int32.MinValue;

            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void lstImagesPoles_KeyUp(object sender, KeyEventArgs e)
        {
            EVendor_Visit_XMissionStructures_Image _tmpImage;
            if (e.KeyCode == Keys.Delete)
            {
                if (lstImagesPoles.SelectedItem != null)
                {
                    _tmpImage = (EVendor_Visit_XMissionStructures_Image)lstImagesPoles.SelectedItem;
                    ((EVendor_Visit_XMissionStructures_Pole)_tmpImage.Pole).Desasocciate(_tmpImage.Id);
                    _tmpImage.IsDesasocciated = true;
                    m_ImagesCurrentPole[m_ImagesCurrentPole.IndexOf(_tmpImage)].IsDesasocciated = true;
                    lstImagesPoles.Items.Remove(_tmpImage);
                    CleanPictureBox();
                }
            }
        }

        private void ddlListImages_KeyDown(object sender, KeyEventArgs e)
        {
            EVendor_Visit_XMissionStructures_Image _tmpImage;
            if (e.KeyCode == Keys.Delete)
            {
                if (ddlListImages.SelectedItem != null)
                {
                    _tmpImage = (EVendor_Visit_XMissionStructures_Image)ddlListImages.SelectedItem;

                    if (_tmpImage.IsDesasocciated)
                    {
                        if (_tmpImage.Asset.Id != Int32.MinValue)
                        {
                            _tmpImage.Asset.DeleteImage(_tmpImage.Id);
                            _tmpImage.Delete();
                        }
                        ddlListImages.Items.Remove(_tmpImage);
                        CleanPictureBox();
                    }
                    else
                    {
                        MessageBox.Show("The image is currently associated with pole " + _tmpImage.Pole.Id.ToString() + ". Please remove the image from pole's information");
                    }
                }
            }
        }

        private void ddlTopType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListBoxItem _SelectedItem;
            _SelectedItem = (ListBoxItem)ddlTopType.SelectedItem;
            if (lstPoles.Items.Count > 0 && Int32.Parse(_SelectedItem.Value) > 0)
            {
                for (int i = 0; i < lstPoles.Items.Count; i++)
                {
                    EVendor_Visit_XMissionStructures_Pole _Pole = (EVendor_Visit_XMissionStructures_Pole)lstPoles.Items[i];
                    _Pole.TopType = new EXMissionStructures_PoleTopType(Int32.Parse(_SelectedItem.Value));
                }
            }
        }

        private void lstPoles_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete && lstPoles.SelectedItem != null)
            {
                EVendor_Visit_XMissionStructures_Pole _pole = (EVendor_Visit_XMissionStructures_Pole)lstPoles.SelectedItem;
                if (_pole.Asset.Id != Int32.MinValue)
                {
                    _pole.Asset.DeletePole(_pole.Id);
                }
                lstPoles.Items.Remove(_pole);
                btnClearPole_Click(this, new EventArgs());
            }
        }


        #endregion

        #region Process
        void _SaveProcess_SaveProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            ShowProgress(e.ProgressPercentage);
        }

        void _SaveProcess_SaveCompleted(object sender, EventArgs e)
        {
            if (m_SelectedStructure != null)
            {
                //Show sucessfull message
                MessageBox.Show("The asset " + m_SelectedStructure.Id.ToString() + " has been saved succesfully");

                m_IsMobileAsset = false;
                m_MobileAssetID = Int32.MinValue;
                m_SelectedStructure = null;
                m_Id = Int32.MinValue;

                //Close
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private delegate void ShowProgressCallback(int p);

        private void ShowProgress(int p)
        {
            if (this.InvokeRequired)
            {
                ShowProgressCallback d = new ShowProgressCallback(ShowProgress);
                this.Invoke(d, new object[] { p });
            }
            else
            {
                pbSave.Value = p;
            }
        }
        #endregion

        #endregion

        #region Private Methods

        private void LoadCombos()
        {
            try
            {
                PPIDesktopClient.General.UIHelper.FillDropDown(ddlProject, LVendor_Project.SelectAllIdName(), typeof(EVendor_Project), "Name", "Vendor_ProjectId", "Select an option...");
                PPIDesktopClient.General.UIHelper.FillDropDown(ddlVisitTypes, LVendor_Visit_Type.SelectAllIdName(), typeof(EVendor_Visit_Type), "Name", "Vendor_Visit_TypeId", "Select an option...");
                PPIDesktopClient.General.UIHelper.FillDropDown(ddlContact, LVendor_Contacts.SelectAllIdName(), typeof(EVendor_Contact), "Name", "Vendor_ContactId", "Select an option...");

                PPIDesktopClient.General.UIHelper.FillDropDown(ddlSpecies, LXMissionStructures_PoleSpecies.SelectAllIdName(), typeof(EXMissionStructures_PoleSpecies), "Name", "XMissionStructures_PoleSpeciesId", "Select an option...");
                PPIDesktopClient.General.UIHelper.FillDropDown(ddlTreatment, LXMissionStructures_PoleTreatments.SelectAllIdName(), typeof(EXMissionStructures_PoleTreatment), "Name", "XMissionStructures_PoleTreatmentId", "Select an option...");
                PPIDesktopClient.General.UIHelper.FillDropDown(ddlClass, LXMissionStructures_PoleClass.SelectAllIdName(), typeof(EXMissionStructures_PoleClass), "Name", "XMissionStructures_PoleClassId", "Select an option...");

                PPIDesktopClient.General.UIHelper.FillDateDropDown(ddlLVisit, 1950, DateTime.Now.Year, 1, "Select an option...");
                PPIDesktopClient.General.UIHelper.FillDateDropDown(ddlYear, DateTime.Now.Year - 100, DateTime.Now.Year, 1, "Select an option...");
                PPIDesktopClient.General.UIHelper.FillLengthDropDown(ddlLength, 30, 100, 5, "Select an option...");
                PPIDesktopClient.General.UIHelper.FillDropDown(ddlHandheld, LHandheld.SelectAllIdName(), typeof(PPIDesktopClient.Entities.EHandheld), "Name", "Id", "Select an option...");

            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmPoleEditor.LoadCombos()", ex.Source, ex.Message, ex.StackTrace);
                throw new Exception(ex.Message);
            }
        }

        private void showImageinPicturebox(FileInfo selectedFile, PictureBox pbx)
        {
            try
            {
                if (selectedFile.Exists)
                {
                    Bitmap _Bitmap = new Bitmap(selectedFile.FullName);
                    pbx.Image = _Bitmap;
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmPoleEditor.showImageinPicturebox()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private void SavePoles(EVendor_Visit_XMissionStructure _Vendor_Visit_XMissionStructure)
        {
            try
            {
                for (int i = 0; i < lstPoles.Items.Count; i++)
                {
                    EVendor_Visit_XMissionStructures_Pole _Vendor_Visit_XMissionStructures_Pole = (EVendor_Visit_XMissionStructures_Pole)lstPoles.Items[i];
                    if (_Vendor_Visit_XMissionStructures_Pole.Id == Int32.MinValue)
                    {
                        _Vendor_Visit_XMissionStructures_Pole.Asset = _Vendor_Visit_XMissionStructure;
                        _Vendor_Visit_XMissionStructure.Poles.Add(_Vendor_Visit_XMissionStructures_Pole);

                    }
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmPoleEditor.SavePoles()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private void SaveImages(EVendor_Visit_XMissionStructure _Vendor_Visit_XMissionStructure)
        {
            try
            {
                EVendor_Visit_XMissionStructures_Image _Image;
                FileInfo _File;
                for (int i = 0; i < ddlListImages.Items.Count; i++)
                {
                    _Image = (EVendor_Visit_XMissionStructures_Image)ddlListImages.Items[i];
                    if (!IsImageInStructure(_Vendor_Visit_XMissionStructure, _Image.File))
                    {
                        _Image.Altitude = crtlPositionStructure.GetAltitude();
                        _Image.Latitude = crtlPositionStructure.GetLatitude();
                        _Image.SatelliteCount = crtlPositionStructure.GetSatelliteCount();
                        _Image.SatelliteTime = crtlPositionStructure.GetSatelliteTime();
                        _Image.Longitude = crtlPositionStructure.GetLongitude();
                        _Image.Asset = _Vendor_Visit_XMissionStructure;
                        _Vendor_Visit_XMissionStructure.Images.Add(_Image);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmPoleEditor.SaveImages()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private bool IsImageInStructure(EVendor_Visit_XMissionStructure vendor_Visit_XMissionStructure, FileInfo file)
        {
            bool _IsInStructure = false;
            foreach (EVendor_Visit_XMissionStructures_Image i in vendor_Visit_XMissionStructure.Images)
            {
                if (i.File.Name == file.Name)
                {
                    _IsInStructure = true;
                    break;
                }
            }
            return _IsInStructure;
        }

        private EVendor_Visit_XMissionStructure SaveStructure()
        {
            try
            {
                ListBoxItem _SelectedItem;
                EVendor_Visit_XMissionStructure _Vendor_Visit_XMissionStructure;
                if (m_SelectedStructure == null)
                {
                    _Vendor_Visit_XMissionStructure = new EVendor_Visit_XMissionStructure();
                    _Vendor_Visit_XMissionStructure.SolutionAvailable = true;
                    _Vendor_Visit_XMissionStructure.Vendor_Contact = new EVendor_Contact();
                    _Vendor_Visit_XMissionStructure.TopType = new EXMissionStructures_TopType();
                    _Vendor_Visit_XMissionStructure.Utility_Asset_XMissionStructure = new EUtility_Asset_XMissionStructure();

                    if (!String.IsNullOrEmpty(m_MobileDatabaseConnectionString))
                    {
                        _Vendor_Visit_XMissionStructure.IsMobile = true;
                        _Vendor_Visit_XMissionStructure.ConnectionString = m_MobileDatabaseConnectionString;
                    }

                }
                else
                {
                    _Vendor_Visit_XMissionStructure = m_SelectedStructure;
                }
                _Vendor_Visit_XMissionStructure.Altitude = crtlPositionStructure.GetAltitude();
                _Vendor_Visit_XMissionStructure.Date = dateDate.Value;
                _Vendor_Visit_XMissionStructure.Latitude = crtlPositionStructure.GetLatitude();
                _Vendor_Visit_XMissionStructure.Longitude = crtlPositionStructure.GetLongitude();
                _Vendor_Visit_XMissionStructure.SatelliteCount = crtlPositionStructure.GetSatelliteCount();
                _Vendor_Visit_XMissionStructure.SatelliteTime = crtlPositionStructure.GetSatelliteTime();

                _Vendor_Visit_XMissionStructure.TopType  = new EXMissionStructures_TopType();

                _SelectedItem = (ListBoxItem)ddlTopType.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                {
                    _Vendor_Visit_XMissionStructure.TopType.XMissionStructures_TopTypeId = Int32.Parse(_SelectedItem.Value);
                }
                _SelectedItem = (ListBoxItem)ddlProject.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                {
                    _Vendor_Visit_XMissionStructure.Vendor_Project = new EVendor_Project(Int32.Parse(_SelectedItem.Value),_SelectedItem.Text);
                }
                _SelectedItem = (ListBoxItem)ddlVisitTypes.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                {
                    _Vendor_Visit_XMissionStructure.Vendor_Visit_Type = new EVendor_Visit_Type(Int32.Parse(_SelectedItem.Value),_SelectedItem.Text);
                }
                _SelectedItem = (ListBoxItem)ddlContact.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                {
                    _Vendor_Visit_XMissionStructure.Vendor_Contact = new EVendor_Contact(Int32.Parse(_SelectedItem.Value));
                    _Vendor_Visit_XMissionStructure.Vendor_Contact.Name = _SelectedItem.Text;
                }
                _SelectedItem = (ListBoxItem)ddlHandheld.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                {
                    _Vendor_Visit_XMissionStructure.Handheld.Name = _SelectedItem.Text;
                    _Vendor_Visit_XMissionStructure.Handheld.Id = Int32.Parse(_SelectedItem.Value);
                }

                _Vendor_Visit_XMissionStructure.Utility_Asset_XMissionStructure = new EUtility_Asset_XMissionStructure();


                return _Vendor_Visit_XMissionStructure;
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmPoleEditor.SaveStructure()", ex.Source, ex.Message, ex.StackTrace);
                return null;
            }

        }

        private bool ValidateControls()
        {
            bool _IsValid = true;
            foreach (Validator _Val in GetAllValidators(tabStructure))
            {
                _Val.Validate();
                _IsValid &= _Val.IsValid;
            }

            _IsValid = (_IsValid && crtlPositionStructure.ValidatePosition());
            if (!_IsValid)
                this.tbcPoleEditor.SelectedTab = tbiStructure;

            return (_IsValid);
        }

        private void LoadPoleData(EVendor_Visit_XMissionStructures_Pole vendor_Visit_XMissionStructures_Pole)
        {

            try
            {
                if (vendor_Visit_XMissionStructures_Pole.Treatment.XMissionStructures_PoleTreatmentId != Int32.MinValue)
                    ddlTreatment.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlTreatment, vendor_Visit_XMissionStructures_Pole.Treatment.XMissionStructures_PoleTreatmentId.ToString());
                if (vendor_Visit_XMissionStructures_Pole.Length != Double.MinValue)
                    ddlLength.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlLength, vendor_Visit_XMissionStructures_Pole.Length.ToString());


                if (vendor_Visit_XMissionStructures_Pole.Species.XMissionStructures_PoleSpeciesId != Int32.MinValue)
                    ddlSpecies.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlSpecies, vendor_Visit_XMissionStructures_Pole.Species.XMissionStructures_PoleSpeciesId.ToString());

                if (vendor_Visit_XMissionStructures_Pole.Class.XMissionStructures_PoleClassId != Int32.MinValue)
                    ddlClass.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlClass, vendor_Visit_XMissionStructures_Pole.Class.XMissionStructures_PoleClassId.ToString());

                if (vendor_Visit_XMissionStructures_Pole.TopType.XMissionStructures_PoleTopTypeId != Int32.MinValue)
                    ddlTopTypePole.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlTopTypePole, vendor_Visit_XMissionStructures_Pole.TopType.XMissionStructures_PoleTopTypeId.ToString());

                ctrlPositionPoles.SetAltitude(vendor_Visit_XMissionStructures_Pole.Altitude);
                ctrlPositionPoles.SetLatitude(vendor_Visit_XMissionStructures_Pole.Latitude);
                ctrlPositionPoles.SetLongitude(vendor_Visit_XMissionStructures_Pole.Longitude);
                ctrlPositionPoles.SetSatelliteCount(vendor_Visit_XMissionStructures_Pole.SatelliteCount);
                ctrlPositionPoles.SetSatelliteTime(vendor_Visit_XMissionStructures_Pole.SatelliteTime);
                txtAID.Text = vendor_Visit_XMissionStructures_Pole.AID;

                if (vendor_Visit_XMissionStructures_Pole.LVisit != Int32.MinValue)
                    ddlLVisit.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlLVisit, vendor_Visit_XMissionStructures_Pole.LVisit.ToString());

                txtLVisitor.Text = vendor_Visit_XMissionStructures_Pole.LVisitor;
                txtNumber.Text = vendor_Visit_XMissionStructures_Pole.Number;

                if (vendor_Visit_XMissionStructures_Pole.Year != Int32.MinValue)
                    ddlYear.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlYear, vendor_Visit_XMissionStructures_Pole.Year.ToString());

                FileInfo _DestinationImagePath;
                m_ImagesCurrentPole = new List<EVendor_Visit_XMissionStructures_Image>();
                if (vendor_Visit_XMissionStructures_Pole.Images != null)
                {
                    foreach (EVendor_Visit_XMissionStructures_Image i in vendor_Visit_XMissionStructures_Pole.Images)
                    {
                        if (!i.IsDesasocciated)
                        {
                            lstImagesPoles.Items.Add(i);
                            m_ImagesCurrentPole.Add(i);

                        }

                    }
                }

                if (ddlLength.SelectedIndex == -1)
                    ddlLength.SelectedIndex = 0;

                if (ddlLVisit.SelectedIndex == -1)
                    ddlLVisit.SelectedIndex = 0;
                if (ddlTopTypePole.SelectedIndex == -1)
                    ddlTopTypePole.SelectedIndex = 0;
                if (ddlClass.SelectedIndex == -1)
                    ddlClass.SelectedIndex = 0;
                if (ddlSpecies.SelectedIndex == -1)
                    ddlSpecies.SelectedIndex = 0;
                if (ddlTreatment.SelectedIndex == -1)
                    ddlTreatment.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmPoleEditor.LoadPoleData()", ex.Source, ex.Message, ex.StackTrace);
            }

        }

        private void CleanPoleControls()
        {
            ddlTreatment.SelectedIndex = 0;
            ddlClass.SelectedIndex = 0;
            ddlSpecies.SelectedIndex = 0;
            //ddlTopTypePole.SelectedIndex = 0;
            ddlLVisit.SelectedIndex = 0;
            ddlYear.SelectedIndex = 0;
            ddlLength.SelectedIndex = 0;
            ctrlPositionPoles.CleanPositions();
            txtLVisitor.Clear();
            txtNumber.Clear();
            txtAID.Clear();
            lstImagesPoles.Items.Clear();
            m_ImagesCurrentPole = new List<EVendor_Visit_XMissionStructures_Image>();
            pbxPoleImagePreview.Image = null;
        }

        private void AddPoleToListbox(ListBox listbox)
        {
            AddPole();
        }

        private void AddPole()
        {
            try
            {
                ListBoxItem _SelectedItem;
                FileInfo _File;
                EVendor_Visit_XMissionStructures_Pole _Vendor_Visit_XMissionStructures_Pole;
                if (lstPoles.SelectedItem == null)
                {
                    _Vendor_Visit_XMissionStructures_Pole = new EVendor_Visit_XMissionStructures_Pole();
                    _Vendor_Visit_XMissionStructures_Pole.SolutionAvailable = true;
                    _Vendor_Visit_XMissionStructures_Pole.Title = lstPoles.Items.Count.ToString();
                }
                else
                {
                    _Vendor_Visit_XMissionStructures_Pole = (EVendor_Visit_XMissionStructures_Pole)lstPoles.SelectedItem;
                    if (m_SelectedStructure != null)
                        _Vendor_Visit_XMissionStructures_Pole.Asset = new EVendor_Visit_XMissionStructure(m_SelectedStructure.Id);
                    else
                        _Vendor_Visit_XMissionStructures_Pole.Asset = new EVendor_Visit_XMissionStructure(Int32.MinValue);
                }
                _Vendor_Visit_XMissionStructures_Pole.AID = txtAID.Text;

                _Vendor_Visit_XMissionStructures_Pole.Altitude = ctrlPositionPoles.GetAltitude();
                _Vendor_Visit_XMissionStructures_Pole.Latitude = ctrlPositionPoles.GetLatitude();
                _Vendor_Visit_XMissionStructures_Pole.Longitude = ctrlPositionPoles.GetLongitude();

                int lvisit;


                _Vendor_Visit_XMissionStructures_Pole.LVisitor = txtLVisitor.Text;
                _Vendor_Visit_XMissionStructures_Pole.Number = txtNumber.Text;
                _Vendor_Visit_XMissionStructures_Pole.SatelliteCount = ctrlPositionPoles.GetSatelliteCount();
                _Vendor_Visit_XMissionStructures_Pole.SatelliteTime = ctrlPositionPoles.GetSatelliteTime();

                _Vendor_Visit_XMissionStructures_Pole.Class = new EXMissionStructures_PoleClass();
                _Vendor_Visit_XMissionStructures_Pole.Species = new EXMissionStructures_PoleSpecies();
                _Vendor_Visit_XMissionStructures_Pole.Treatment = new EXMissionStructures_PoleTreatment();
                _Vendor_Visit_XMissionStructures_Pole.TopType = new EXMissionStructures_PoleTopType();

                _SelectedItem = (ListBoxItem)ddlLVisit.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                    _Vendor_Visit_XMissionStructures_Pole.LVisit = Int32.Parse(_SelectedItem.Value); ;

                _SelectedItem = (ListBoxItem)ddlYear.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                    _Vendor_Visit_XMissionStructures_Pole.Year = Int32.Parse(_SelectedItem.Value); ;

                _SelectedItem = (ListBoxItem)ddlClass.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                    _Vendor_Visit_XMissionStructures_Pole.Class.XMissionStructures_PoleClassId = Int32.Parse(_SelectedItem.Value);

                _SelectedItem = (ListBoxItem)ddlSpecies.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                    _Vendor_Visit_XMissionStructures_Pole.Species.XMissionStructures_PoleSpeciesId = Int32.Parse(_SelectedItem.Value);

                _SelectedItem = (ListBoxItem)ddlTreatment.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                    _Vendor_Visit_XMissionStructures_Pole.Treatment.XMissionStructures_PoleTreatmentId = Int32.Parse(_SelectedItem.Value);

                _SelectedItem = (ListBoxItem)ddlTopTypePole.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                    _Vendor_Visit_XMissionStructures_Pole.TopType.XMissionStructures_PoleTopTypeId = Int32.Parse(_SelectedItem.Value);
                _SelectedItem = (ListBoxItem)ddlLength.SelectedItem;
                if (Int32.Parse(_SelectedItem.Value) > 0)
                    _Vendor_Visit_XMissionStructures_Pole.Length = double.Parse(_SelectedItem.Value);



                _Vendor_Visit_XMissionStructures_Pole.Images.Clear();
                _Vendor_Visit_XMissionStructures_Pole.DesasocciateImages.Clear();
                foreach (EVendor_Visit_XMissionStructures_Image _Image in m_ImagesCurrentPole)
                {
                    if (!_Image.IsDesasocciated)
                    {
                        _Image.IsDesasocciated = false;
                        _Image.Altitude = ctrlPositionPoles.GetAltitude();
                        _Image.Latitude = ctrlPositionPoles.GetLatitude();
                        _Image.SatelliteCount = ctrlPositionPoles.GetSatelliteCount();
                        _Image.SatelliteTime = ctrlPositionPoles.GetSatelliteTime();
                        _Image.Longitude = ctrlPositionPoles.GetLongitude();
                        _Image.Pole = _Vendor_Visit_XMissionStructures_Pole;
                        _Vendor_Visit_XMissionStructures_Pole.Images.Add(_Image);
                        _Image.Asset = _Vendor_Visit_XMissionStructures_Pole.Asset;                    
                    }

                }
                if (lstPoles.SelectedItem != null)
                {
                    lstPoles.SelectedItem = _Vendor_Visit_XMissionStructures_Pole;
                }
                else
                {
                    lstPoles.Items.Add(_Vendor_Visit_XMissionStructures_Pole);
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmPoleEditor.AddPole()", ex.Source, ex.Message, ex.StackTrace);
            }
        }

        private void RemoveImage()
        {
            if (ddlListImages.SelectedItem != null)
            {

                ddlImagesPole.Items.Remove(ddlListImages.SelectedItem);
                lstImagesPoles.Items.Remove(ddlListImages.SelectedItem);
                ddlListImages.Items.Remove(ddlListImages.SelectedItem);
                m_ImagesCurrentPole.Remove((EVendor_Visit_XMissionStructures_Image)ddlListImages.SelectedItem);
            }
        }

        private void CleanPictureBox()
        {
            pbxPoleImagePreview.Image = null;
            pbxSelectedImage.Image = null;
        }

        private void LoadStructureData(EVendor_Visit_XMissionStructure vendor_Visit_XMissionStructure)
        {
            try
            {
                FileInfo _DestinationImagePath;
                if (vendor_Visit_XMissionStructure.Vendor_Project.Vendor_ProjectId != Int32.MinValue)
                    ddlProject.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlProject, vendor_Visit_XMissionStructure.Vendor_Project.Vendor_ProjectId.ToString());

                if (vendor_Visit_XMissionStructure.Vendor_Visit_Type.Vendor_Visit_TypeId != Int32.MinValue)
                    ddlVisitTypes.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlVisitTypes, vendor_Visit_XMissionStructure.Vendor_Visit_Type.Vendor_Visit_TypeId.ToString());

                if (vendor_Visit_XMissionStructure.TopType.XMissionStructures_TopTypeId != Int32.MinValue)
                    ddlTopType.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlTopType, vendor_Visit_XMissionStructure.TopType.XMissionStructures_TopTypeId.ToString());

                if (vendor_Visit_XMissionStructure.Vendor_Contact.Vendor_ContactId != Int32.MinValue)
                    ddlContact.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlContact, vendor_Visit_XMissionStructure.Vendor_Contact.Vendor_ContactId.ToString());


                dateDate.Value = vendor_Visit_XMissionStructure.Date;
                if (vendor_Visit_XMissionStructure.Handheld.Id != Int32.MinValue)
                    ddlHandheld.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlHandheld, vendor_Visit_XMissionStructure.Handheld.Id.ToString());
                
                crtlPositionStructure.SetAltitude(vendor_Visit_XMissionStructure.Altitude);
                crtlPositionStructure.SetLatitude(vendor_Visit_XMissionStructure.Latitude);
                crtlPositionStructure.SetLongitude(vendor_Visit_XMissionStructure.Longitude);
                crtlPositionStructure.SetSatelliteCount(vendor_Visit_XMissionStructure.SatelliteCount);
                crtlPositionStructure.SetSatelliteTime(vendor_Visit_XMissionStructure.SatelliteTime);

                lstPoles.Items.Clear();
                foreach (EVendor_Visit_XMissionStructures_Pole p in vendor_Visit_XMissionStructure.Poles)
                {
                    lstPoles.Items.Add(p);
                }
                ddlListImages.Items.Clear();
                ddlImagesPole.Items.Clear();
                lstImagesPoles.Items.Clear();
                foreach (EVendor_Visit_XMissionStructures_Image i in vendor_Visit_XMissionStructure.Images)
                {
                    ddlListImages.Items.Add(i);
                    ddlImagesPole.Items.Add(i);
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmPoleEditor.LoadStructureData()", ex.Source, ex.Message, ex.StackTrace);
                throw new Exception(ex.Message);
            }
        }

        private EVendor_Visit_XMissionStructure SelectStructure(int m_Vendor_Visit_XMissionStructureID)
        {
            try
            {
                return LVendor_Visit_XMissionStructure.GetStructure(m_Vendor_Visit_XMissionStructureID);
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmPoleEditor.SelectStructure()", ex.Source, ex.Message, ex.StackTrace);
                throw new Exception(ex.Message);
            }
        }
        private EBaseAsset SelectStructure(EBaseAsset assset)
        {
            try
            {
                return assset.GetServer();
            }
            catch (Exception ex)
            {
                //ErrorManager.Log("frmPoleEditor.SelectStructure()", ex.Source, ex.Message, ex.StackTrace);
                throw ex;
                //return null;
            }
        }

        private void CleanStructureData()
        {
            dateDate.Value = DateTime.MinValue;
            crtlPositionStructure.CleanPositions();
            ddlHandheld.Items.Clear();
            ddlListImages.Items.Clear();
            txtImageName.Clear();
            pbxSelectedImage.Image = null;
            pbSave.Value = 0;
        }

        private EVendor_Visit_XMissionStructure SelectMobileStructure(int MobileAssetID)
        {
            return LVendor_Visit_XMissionStructure.GetStructureFromMobileVisit(MobileAssetID, m_MobileDatabaseConnectionString);
        }

        #endregion

        #region Public Methods

        public void DeleteStructure(int structureID)
        {
            try
            {
                if (!IsMobileAsset)
                {
                    //Database delete
                    LVendor_Visit_XMissionStructure.Delete(structureID);

                    XMLHelperDownloadImage _DownloadedImages = new XMLHelperDownloadImage(Constants.k_XmlImagePath);
                    _DownloadedImages.DeleteImages(structureID);
                }
                else
                {
                    LogicLayer.DeleteCompleteVisit(structureID, m_MobileDatabaseConnectionString);
                }
                //Show sucessfull message
                MessageBox.Show("The asset " + structureID + " has been deleted succesfully");

            }
            catch (Exception ex)
            {
                ErrorManager.Log("Exception", "frmPoleEditor " + ex.Source, ex.Message, ex.StackTrace);
            }
        }

        public void DeleteStructure(EBaseAsset structure)
        {
            try
            {
                structure.Delete();
                //Show sucessfull message
                MessageBox.Show("The asset " + structure.Id + " has been deleted succesfully");

            }
            catch (Exception ex)
            {
                ErrorManager.Log("Exception", "frmPoleEditor " + ex.Source, ex.Message, ex.StackTrace);
            }
        }

        #endregion

        #region Constructor

        public frmPoleEditor()
        {
            InitializeComponent();
        }

        #endregion

        private void ddlVisitTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlVisitTypes.SelectedIndex > 0)
            {
                int selectedType = Int32.Parse(((ListBoxItem)ddlVisitTypes.SelectedItem).Value);
                PPIDesktopClient.General.UIHelper.FillDropDown(ddlTopType, LXMissionStructures_TopType.SelectAllIdNameListByType(selectedType), typeof(EXMissionStructures_TopType), "Name", "XMissionStructures_TopTypeId", "Select an option...");
                PPIDesktopClient.General.UIHelper.FillDropDown(ddlTopTypePole, LXMissionStructures_TopType.SelectAllIdNameListByType(selectedType), typeof(EXMissionStructures_TopType), "Name", "XMissionStructures_TopTypeId", "Select an option...");
            }
        }

    }
}
